package com.by.rpc.config;

import com.by.log.Logger;
import com.by.log.LoggerFactory;
import com.by.rpc.client.RpcReferenceBeanPostProcessor;
import com.by.rpc.client.RpcReferenceHealthChecker;
import com.by.rpc.factory.RpcClientFactory;
import com.by.rpc.registry.ServiceRegistry;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RPC客户端自动配置类
 */
@Configuration
@EnableConfigurationProperties(RpcProperties.class)
@ConditionalOnBean(ServiceRegistry.class) // 确保在ServiceRegistry存在时才加载
public class RpcClientAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(RpcClientAutoConfiguration.class);

    private final RpcProperties rpcProperties;
    private final ObjectProvider<ServiceRegistry> serviceRegistryProvider;

    public RpcClientAutoConfiguration(RpcProperties rpcProperties,
                                      ObjectProvider<ServiceRegistry> serviceRegistryProvider) {
        this.rpcProperties = rpcProperties;
        this.serviceRegistryProvider = serviceRegistryProvider;
        logger.info("Initializing RPC client auto configuration.");
    }

    /**
     * 定义RPC客户端的BeanPostProcessor
     * 添加@Order注解来明确其执行顺序，避免与Spring内部的BeanPostProcessor冲突。
     */
    @Bean
    @ConditionalOnMissingBean
    public RpcReferenceBeanPostProcessor rpcReferenceBeanPostProcessor() {
        return new RpcReferenceBeanPostProcessor(rpcProperties, serviceRegistryProvider);
    }

    /**
     * 定义RPC客户端健康检查器，并注入BeanPostProcessor
     * 修复：不再注入RpcReferenceBeanPostProcessor，而是直接使用ObjectProvider获取ServiceRegistry
     */
    @Bean
    @ConditionalOnMissingBean
    public RpcReferenceHealthChecker rpcReferenceHealthChecker() {
        return new RpcReferenceHealthChecker(serviceRegistryProvider, rpcProperties);
    }

    /**
     * 定义RPC客户端工厂
     */
    @Bean(destroyMethod = "shutdown")
    @ConditionalOnMissingBean
    public RpcClientFactory rpcClientFactory() {
        return RpcClientFactory.getInstance();
    }
}
